package com.tjh.hive_data_compare;

import com.tjh.hive_data_compare.util.HiveUtil;
import com.tjh.hive_data_compare.util.JavaFileUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.List;

public class StartGetTable {
    private static final Logger logger = LogManager.getLogger(StartGetTable.class);

    public static void main(String[] args) {
        //第一个参数hiveserver地址，第二个参数默认数据库,第三个文件目录，第四个库名，第五个账号，第六个密码
        String serverAddress = "192.168.83.176";
        String setDB = "dw_ods";
        String filePath = "D:\\tt.txt";
        String dbList = "dw_ods";
        String userName = "";
        String passWord = "";
        if (args.length == 3) {
            serverAddress = args[0];
            setDB = args[1];
            filePath = args[2];
        }

        if (args.length == 4) {
            serverAddress = args[0];
            setDB = args[1];
            filePath = args[2];
            dbList = args[3];
        }

        if (args.length == 6) {
            userName = args[4];
            passWord = args[5];
        }
        HiveUtil hiveUtil = new HiveUtil();
        try {
            hiveUtil.init(serverAddress, userName, passWord, setDB);
            List<String> dataBaseList = hiveUtil.showDatabases();
            if (dataBaseList != null && dataBaseList.size() > 0) {
                for (String tmpDB : dataBaseList) {
                    //只要需要校验的库
                    if (dbList.contains(tmpDB)) {
                        HiveUtil hiveUtilTable = new HiveUtil();
                        hiveUtilTable.init(serverAddress, userName, passWord, tmpDB);
                        List<String> tableList = hiveUtilTable.showTables();
                        hiveUtilTable.destory();
                        //生成msck文件
                        if (tableList != null && tableList.size() > 0) {
                            for (String tmpTable : tableList) {
                                String content = "msck repair table " + tmpDB + "." + tmpTable + ";";
                                System.out.println(content);
                                JavaFileUtil.writeInFile(filePath, content);
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            logger.error("操作hive异常:" + ex);
            System.out.println("操作hive异常:" + ex.getMessage());
        } finally {
            try {
                hiveUtil.destory();
            } catch (Exception e) {
                logger.error("关闭hive链接异常:" + e);
                System.out.println("关闭hive链接异常:" + e.getMessage());
            }
        }

    }
}
